var Main = {
	serverURL: 'http://localhost:8888/recommender/list', //In future, try to obtain value from a property in config.xml file
    clientId: null,
    programList: null,
	profile: null,
	now: null,
    to: 7200 //In future, try to obtain this value from a property in config.xml file
}

var now = null;
var interval = null;
var previousChannel = null;
var previousProgram = null;
var profileFilename = 'profile.dat'; //In future, try to obtain this value from a property in config.xml file

var widgetAPI = new Common.API.Widget(); // Create Common module

Main.onLoad = function () {
    previousChannel = windowObject.GetCurrentChannel_Name();
    previousProgram = tvObject.GetPresentProgram_Title();
    now = timeObject.GetEpochTime();
	tvObject.SetEvent(PL_TV_EVENT_CHANNEL_CHANGED);
    tvObject.OnEvent = OnEvent;

    var list = this.getProgramList();
    
    for (p in list) {
        alert(list[p]);
    }

    this.clientId = tvObject.GetTimeZone() + ':' + tvObject.GetCountry() + ':' + tvObject.GetProductType() +
        ':' + tvObject.GetProductCode(1);

    this.sendRequests(); //Send program list

	widgetAPI.sendReadyEvent();
}

Main.sendRequests = function () {
    var XHRObject = new XMLHttpRequest();

	if (XHRObject) {
        XHRObject.open("POST", this.serverURL, false);
        this.profile = this.buildProfile();
        XHRObject.send(this.profile);
        alert(XHRObject.responseText);
        XHRObject.destroy();
	}
}

Main.buildProfile = function () {
    var profileElement = '<client-profile id="' + this.clientId + '">';
    var epgProgramListElement = this.buildProgramList();
    var currentProgramElement = '<current-program title="' + tvObject.GetPresentProgram_Title() + '" channel="' + windowObject.GetCurrentChannel_Name() +'"/>';
    var preferedProgramsElement = '<prefered-programs>';
    var preferedPrograms = this.getPreferedPrograms();

    for (i in preferedPrograms) {
        preferedProgramsElement += preferedPrograms[i];
    }
    preferedProgramsElement += '</prefered-programs>';

    profileElement += epgProgramListElement + currentProgramElement + preferedProgramsElement + '</client-profile>';

    return profileElement;
}

Main.getPreferedPrograms = function () {
	var fileSystemObject = new FileSystem();
	var handler = fileSystemObject.openCommonFile(profileFilename, 'r+');
    var programList = new Array();

    if (handler == null) {
		handler = fileSystemObject.openCommonFile(profileFilename, 'w');
        fileSystemObject.closeCommonFile(handler);
        return new Array();
	}

    var line;
    for (var i = 0; (line = handler.readLine()) != null; i++) {
        programList[i] = '<program title="' + line.substring(0, line.indexOf("|"))
		+ '" channel="' + line.substring(line.indexOf("|")+1, line.lastIndexOf("|"))
		+ '" rating="' + line.substring(line.lastIndexOf("|")+1) + '"/>';
    }
    fileSystemObject.closeCommonFile(handler);

    return programList;
}

Main.buildProgramList = function () {
    var programListElement = '<program-list channel="' + windowObject.GetCurrentChannel_Name() + '">';
    var programList = this.getProgramList();

    for (i in programList) {
        programListElement += '<program title="' + programList[i] + '"/>';
    }
    programListElement += '</program-list>';

    return programListElement;
}

Main.getProgramList = function () {
    tvObject.GetProgramList(timeObject.GetEpochTime(), 3600*24);
    var programList = new Array();
    var programListSize = tvObject.GetProgramList_Size();

    for (var i = 0; i < programListSize; i++) {
        programList[i] = tvObject.GetProgram_Title(i);
    }

    return programList;
}

function OnEvent(e) {
    switch (parseInt(e)) {
    case PL_TV_EVENT_CHANNEL_CHANGED:
        alert(windowObject.GetCurrentChannel_Name());
        var average = ((timeObject.GetEpochTime() - now) / tvObject.GetPresentProgram_Duration()).toFixed(2);
        //var average = 0.2;

        //alert(previousProgram);

        if (average >= 0.1) {
            var fileSystemObject = new FileSystem();
            var handler = fileSystemObject.openCommonFile(profileFilename, 'r+');

            if (handler == null) {
                handler = fileSystemObject.openCommonFile(profileFilename, 'w');
                handler.writeLine(previousProgram + '|' + previousChannel + '|' + average + "\n");
            } else {
                var lines = new Array();
                var updatedLineIndex = -1;
                var updatedLine;

                for (var i = 0; (line = handler.readLine()) != null; i++) {
                    lines[i] = line;
                    if (line.substring(0, line.indexOf("|")) == previousProgram) {
                        var programTitle = line.substring(0, line.indexOf("|"));
						var channelName = line.substring(line.indexOf("|")+1, line.lastIndexOf("|"));
                        var oldAverage = parseFloat(line.substring(line.lastIndexOf("|")+1));
                        var newAverage = ((average + oldAverage) / 2).toFixed(2);

                        updatedLine = programTitle + '|' + channelName + '|' + newAverage;
                        updatedLineIndex = i;
                    }
                }

                if (updatedLineIndex == -1) {
                    handler.writeLine(previousProgram + '|' + previousChannel + '|' + average);
                } else {
                    var fileContent = '';
                    handler.writeAll(fileContent);

                    for (var i = 0; i < lines.length; i++) {
                        if (i == updatedLineIndex)
                            fileContent += updatedLine + "\n";
                        else
                            fileContent += lines[i] + "\n";
                    }
                    handler.writeAll(fileContent);
                }
            }
            fileSystemObject.closeCommonFile(handler);
        }
        now = timeObject.GetEpochTime();
        previousChannel = windowObject.GetCurrentChannel_Name();
        previousProgram = tvObject.GetPresentProgram_Title();

        break;
    }
}